#!/usr/bin/env bash

set -e

# 安装必要的软件
ai() {
	sudo apt install "$@" -y
}
sudo ln -s $(which python3) /usr/local/bin/python
ai python3 ruby python3-pip git-lfs gcc g++ zlib1g-dev libc++1 curl nodejs npm bison ccache default-jdk flex libtinfo5 genext2fs u-boot-tools mtools mtd-utils scons build-essential libc6-dev

# 安装repo工具
sudo curl https://gitee.com/oschina/repo/raw/fork_flow/repo-py3 -o /usr/local/bin/repo
sudo chmod a+x /usr/local/bin/repo
pip3 install -i https://repo.huaweicloud.com/repository/pypi/simple requests

# 下载源码
mkdir -p ~/document/oh
cd ~/document/oh
# 这里修改成自己的信息
git config --global user.email "mrgeek-zrh@outlook.com"
git config --global user.name "MrGeek-zrh"
repo init -u https://gitee.com/riscv-sig/manifest.git -b weekly -m riscv64_weekly0905_init.xml --no-repo-verify
repo sync -c -j4
repo forall -c "git lfs pull"

# 安装编译器及二进制工具
./build/prebuilts_download.sh

# 首先需要全量编译代码
./build.sh --product-name rk3568

# 测试arkcompiler编译情况
# 编写一个hello world实例测试一下：
cd ~/document/oh
CURRENT_PATH=$(pwd)
cat <<EOF >test/test.ts
declare function print(arg:string):string;
print('Hello world!');
EOF

# 写个小脚本，将ts文件编译成字节码文件
cat <<EOF >test/build2abc.sh
#!/usr/bin/env bash
$CURRENT_PATH/out/rk3568/clang_x64/arkcompiler/ets_frontend/es2abc --output ${CURRENT_PATH}/test/test.abc \$1
EOF

# 赋予执行权限
chmod +x test/build2abc.sh

# 编译ts文件
test/build2abc.sh $CURRENT_PATH/test/test.ts

# 编写执行字节码文件的脚本
cat <<EOF >test/run.sh
LD_LIBRARY_PATH=./out/rk3568/clang_x64/arkcompiler/ets_runtime/:out/rk3568/clang_x64/thirdparty/icu:out/rk3568/clang_x64/thirdparty/zlib:prebuilts/clang/ohos/linux-x86_64/llvm/lib ./out/rk3568/clang_x64/arkcompiler/ets_runtime/ark_js_vm ./test/test.abc
EOF

# 执行脚本
chmod +x test/run.sh
test/run.sh

# 验证实验八的功能
# 后续只需要编译指定模块
# 由于实验八的代码已经被其他人合并，所以我们直接删除官方的ark compiler代码，换成我们自己的
cd arkcompiler/ets_runtime
git remote remove origin
git remote set-url origin git@gitee.com:advanced_os_ucas/arkcompiler_ets_runtime.git
git checkout dev
git fetch origin
git reset --hard origin/dev
git pull origin dev --force
./build.sh --product-name rk3568 --build-target ark_compiler_unittest

# 运行测试用例
LD_LIBRARY_PATH=out/rk3568/clang_x64/arkcompiler/ets_runtime:out/rk3568/clang_x64/thirdparty/zlib:out/rk3568/clang_x64/thirdparty/bounds_checking_function:out/rk3568/clang_x64/thirdparty/icu:oh/prebuilts/clang/ohos/linux-x86_64/llvm/lib ./out/rk3568/clang_x64/tests/unittest/arkcompiler/ets_runtime/AssemblerTest
